package cn.jihhhh.chatgpt.data.domain.order.service.pay.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.jihhhh.chatgpt.data.domain.order.model.valobj.PayOrderRequestVO;
import cn.jihhhh.chatgpt.data.domain.order.service.pay.IPayFilter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import static com.github.houbb.heaven.util.secrect.Md5Util.md5;

/**
 * 蓝兔支付
 *
 * @author JIHHHH
 * @date 2025-02-06
 */
@Slf4j
@Service("blueRabbitPayFilter")
public class BlueRabbitPayFilter implements IPayFilter {
    @Value("${brpay.config.mchid}")
    private String muchId;
    @Value("${brpay.config.api-v3-key}")
    private String pwdKey;
    @Value("${brpay.config.notify-url}")
    private String notifyUrl;
    @Override
    public String doPrepayOrder(PayOrderRequestVO payOrderRequestVO) {
        Map<String, String> params = new HashMap<>();
        params.put("mch_id", muchId);

        params.put("out_trade_no", payOrderRequestVO.getOrderId());
        params.put("total_fee", String.valueOf(payOrderRequestVO.getAmountTotal()));

        params.put("body", payOrderRequestVO.getProductName());
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000L);
        params.put("timestamp", timestamp);
        params.put("notify_url", notifyUrl);
        String sign = createSign(params, pwdKey);

        String body = "mch_id=" + muchId +
                "&out_trade_no=" + payOrderRequestVO.getOrderId() +
                "&total_fee=" + payOrderRequestVO.getAmountTotal() +
                "&body=" + payOrderRequestVO.getProductName() +
                "&timestamp=" + timestamp +
                "&notify_url=" + notifyUrl +
                "&time_expire=15m&sign=" + sign;
        // 发送HTTP请求
        HttpResponse execute = HttpRequest.post("https://api.ltzf.cn/api/wxpay/native")
                .header("content-type", "application/x-www-form-urlencoded")
                .body(body)
                .execute();

        body = execute.body();
        JSONObject jsonObject = JSON.parseObject(body);
        return jsonObject.getJSONObject("data").getString("code_url");
    }


    protected String packageSign(Map< String, String > params, boolean urlEncoder) {
        // 先将参数以其参数名的字典序升序进行排序
        TreeMap< String, String > sortedParams = new TreeMap < String, String > (params);
        // 遍历排序后的字典，将所有参数按"key=value"格式拼接在一起
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (Map.Entry< String, String > param: sortedParams.entrySet()) {
            String value = param.getValue();
            if (StringUtils.isBlank(value)) {
                continue;
            }
            if (first) {
                first = false;
            } else {
                sb.append("&");
            }
            sb.append(param.getKey()).append("=");
            if (urlEncoder) {
                try {
                    value = urlEncode(value);
                } catch (UnsupportedEncodingException e) {}
            }
            sb.append(value);
        }
        return sb.toString();
    }

    protected String urlEncode(String src) throws UnsupportedEncodingException {
        return URLEncoder.encode(src, Charsets.UTF_8.name()).replace("+", "%20");
    }

    protected String createSign(Map < String, String > params, String partnerKey) {
        // 生成签名前先去除sign
        params.remove("sign");
        String stringA = packageSign(params, false);
        String stringSignTemp = stringA + "&key=" + partnerKey;
        return md5(stringSignTemp).toUpperCase();
    }
}
